#include <Arduino.h>
#include "com/communication.h"
#include "message.h"
#include "protocol.h"

#define BUTTON 3
#define RF24 2

volatile bool button_pressed = false;
extern volatile bool received_msg;

void pair_with_slave();

int main(void) {
	init();

	setup();

	for (;;)
		loop();

	return 0;
}



void button_interrupt() {
	button_pressed = true;
}

void setup() {
	//pinMode(RF24, INPUT); // RF24 Interrupt pin - not used at the moment
	pinMode(BUTTON, INPUT); // Button Interrupt pin
	digitalWrite(BUTTON, HIGH);

	Serial.begin(9600);
	Serial.println("I\'m the master!");

	attachInterrupt(1, button_interrupt, FALLING);

	com_activate_debug();
	com_init_master();

	delay(500);
	button_pressed = false;
}

void loop() {
	if(button_pressed) { // Pairing
		delay(100);
		button_pressed = false;
		if(digitalRead(BUTTON) == LOW)
			return;
		Serial.println("Start pairing...");
		pair_with_slave();
	}

	int value_type = 0;
	if(com_num_slaves() > 0 && com_available()) {
		for(uint8_t i = 1; i <= com_num_slaves(); i++) {
			message msg = com_read_msg_from_slave(i, 100); // No timeout as we know that a message has been received
			if(msg.getMsgType() == ERROR) // This was not the slave that has sent a message
				continue;

			Serial.print("Msg Type: ");
			Serial.println(msg.getMsgTypeString());

			if(msg.getMsgType() == SENSOR_DESCRIPTION) {
				Serial.print("Sensor Type: ");
				Serial.println(msg.getSensorTypeString());
				Serial.print("Value Type: ");
				Serial.println(msg.getValueTypeString());
				value_type = msg.getValueType();
			} else {
				unsigned int valUI;
				int valI;
				float valF;
				Serial.print("Value: ");
				switch(msg.getMsgType()) {
					case UINT8:
					case UINT16:
					case UINT32:
						valUI = msg.getUInt();
						Serial.println(valUI);
						break;
					case INT8:
					case INT16:
					case INT32:
						valI = msg.getInt();
						Serial.println(valI);
						break;
					case FLOAT:
						valF = msg.getFloat();
						Serial.println(valF, 3);
						break;
				}
			}

		}

	}
}

void pair_with_slave() {
	if(com_pair_with_slave())
		Serial.println("Successfully paired with slave");
}
